<template>
    <div ref="elToolbar" class="co-el-toolbar">
        <div class="co-toolbar box-row">
            <el-form-item label="分类:"  size="default">
                <el-select class="co-cat-select" v-model="params.cat_id" @change="load">
                <el-option
                    v-for="item in category"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
            </el-select>
            </el-form-item>
            <el-form-item label="状态:" size="default" v-if="isRack">
                <el-select class="co-onsale-select" v-model="params.on_sale">
                    <el-option :value="0" label="所有"></el-option>
                    <el-option :value="true" label="允许销售"></el-option>
                    <el-option :value="false" label="停止销售"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="条件:" size="default" >
                <el-input class="co-search-input" placeholder="请输入商品名称或条码" v-model="params.code" clearable></el-input>
            </el-form-item>
            <el-button type="primary" @click="onSearch">查找</el-button>
            <span style="flex:1"></span>

            <el-button type="primary" @click="ShowStockCheckDialog">盘点</el-button>
            
            <el-button-group v-if="showOp">
                <el-button type="success" :disabled="selectedNum==0" @click="ShowInOutDialog(true)">进货<template v-if="selectedNum > 0">({{ selectedNum }})</template></el-button>
                <el-button type="warning" :disabled="selectedNum==0" @click="ShowInOutDialog(false)">出货<template v-if="selectedNum > 0">({{ selectedNum }})</template></el-button>
                <template v-if="stores.length > 0">
                    <el-button type="primary" :disabled="selectedNum==0" @click="ShowRackonDialog(false)">下架<template v-if="selectedNum > 0">({{ selectedNum }})</template></el-button>
                    <el-button type="primary" :disabled="selectedNum==0" @click="ShowRackonDialog(true)">上架<template v-if="selectedNum > 0">({{ selectedNum }})</template></el-button>
                </template>
            </el-button-group>
        </div>
    </div>
    <el-table :data="data" :height="h" size="small">
        <el-table-column prop="id" width="60" type="selection"></el-table-column>
        <el-table-column prop="category_ids" label="分类" >
            <template v-slot:default="scope">
                <span v-category="{v:scope.row.category_ids, tpl:cats}"></span>
            </template>
        </el-table-column>
        <el-table-column prop="name" label="商品名" ></el-table-column>
        <el-table-column prop="sale_price" label="售价" :width="88" align="right" :formatter="rmbFormatter"></el-table-column>
        <el-table-column prop="code" label="条码" :width="120" align="center"></el-table-column>
        <el-table-column prop="store_num" label="库存" :width="80" align="right">
            <template v-slot:default="scope">
                <span v-if="scope.row.prop != 1">{{scope.row.store_num}}</span>
                <span v-else>不计</span>
            </template>
        </el-table-column>
        <el-table-column v-if="isRack" prop="on_sale" label="可售" :width="88" align="center" >
            <template v-slot:default="scope">
                <el-switch size="small" v-model="scope.row.on_sale" @click="onSetOnSale(scope.row)"></el-switch>
            </template>
        </el-table-column>
        <el-table-column prop="store_num" width="90" align="center">
            <template #header>
                <el-dropdown>
                    <el-link type="primary">选择</el-link>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item @click="onSelAll">全选</el-dropdown-item>
                            <el-dropdown-item @click="onDeSell">反选</el-dropdown-item>
                            <el-dropdown-item divided @click="onCancelSel">取消</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
                
            </template>
            <template v-slot:default="{row}">
                <el-button v-if="!row.selected" size="small" type="success" :disabled="row.prop == 1" @click="onAddSel(row)">加入</el-button>
                <el-button v-else size="small" type="danger" :disabled="!row.prop != 1" @click="onRemoveSel(row)">移除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <div class="ui-pagination-ctn box-row">
        <div class="flex"></div>
        <el-pagination
            v-model:current-page="params.page" :page-size="params.limit" :page-sizes="[23, 50, 100, 200]"
            layout="sizes, total, prev, pager, next" :total="total" 
            @size-change="onPageSizeChange" @current-change="onPageChange"
        ></el-pagination>
    </div>
</template>
<script>
import { computed,reactive, toRefs,watch,ref } from 'vue-demi';
import {useElementSize} from '@vueuse/core'
import { useSocket } from '../../uiframe/services/socket';
import { ElMessage } from 'element-plus';
import { UiShowDialog } from '../../uiframe/layout/components/CompFactory.vue';
import RackOnDialog from './RackOnDialog.vue';
import { dict, rmbFormat } from '../../uiframe/utils';
import directives from '../../uiframe/services/directives';
import InOutDialog from './InOutDialog.vue';
import StoreCheckDialog from './StoreCheckDialog.vue';

export default {
    directives,
    props:{
        storeId: Number,
        mh: Number,
        show: Boolean,
        isRack:Boolean,
        stores:Array,
        showOp:Boolean
    },

    setup:(props)=>{
        let inited = false, elToolbar = ref(null);
        const storeId = props.storeId, onmessage = (msg) => { ElMessage({ type: msg.success ? 'success' : 'error', message: msg.message }) },
        data = reactive({
            tbsize: useElementSize(elToolbar),
            h:computed(()=>{
                return props.mh - (data.tbsize.height + 34);
            }),
            category: [],
            cats:{},
            data:[],
            total:0,
            selectedNum:0,
            params:{
                page:1, limit:23,
                store_id:storeId, 
                cat_id: null, 
                on_sale:0,
                code:''
            },
        }),
        init = ()=>{
            useSocket().then(socket=>{
                socket.rpc('category',{}).then(({success, data:result})=>{
                    data.category = result;
                    data.cats = dict(result, 'id');
                    data.params.cat_id = result[0].id;
                    load();
                })
                
            })
        }, load = ()=>{
            useSocket().then(socket=>{
                Promise.all([socket.rpc('StoreComponents',data.params).then(({success, data:result})=>{
                    data.data = result.data;
                    data.total = result.total;
                    //console.log('StoreComponents:', success, result);
                }),socket.rpc('sel.num',{store_id: storeId}).then(({success, data:result})=>{
                    data.selectedNum = result
                    //console.log('selnum:', success, result);
                })]).then(res=>{
                    data.loading = false
                    console.log('all done!');
                })
            })
        },
        methods = {
            onSizeChange:(e)=>{
                data.th = data.toolbar.offsetHeight;
            },
            onPageChange:()=>{
                load();
            },
            onPageSizeChange:(size)=>{
                data.params.limit = size;
                load();
            },
            onSearch:()=>{
                data.params.page = 1;
                load();
            },
            onSetOnSale:(row)=>{
                useSocket().then(socket=>socket.rpc('set_on_sale', {store_id:storeId, goods_id: row.id, on_sale:row.on_sale}).then(res=>{
                    onmessage(res);
                    if(res.data.hasOwnProperty('on_sale')){row.on_sale = res.data.on_sale;}
                }).catch(res=>{
                    onmessage(res);
                    if(res.data.hasOwnProperty('on_sale')){row.on_sale = res.data.on_sale;}
                }))
            },
            onAddSel:(row)=>{
                useSocket().then(socket=>socket.rpc('sel.add',{store_id: storeId, goods_id:row.id}).then(res=>{
                    if(res.success){
                        row.selected = true;
                        data.selectedNum ++;
                    }
                    onmessage(res);
                }).catch(res=>{
                    onmessage(res);
                }))
            },
            onRemoveSel:(row)=>{
                useSocket().then(socket=>socket.rpc('sel.rm',{store_id: storeId, goods_id:row.id}).then(res=>{
                    if(res.success){
                        data.selectedNum --;
                        row.selected = false;
                    }
                    console.log('rmsel:', res);
                    onmessage(res);
                }).catch(res=>{
                    onmessage(res);
                }))
            },
            onSelAll:()=>{
                useSocket().then(socket=>socket.rpc('sel.selall',{store_id: storeId}).then(res=>{
                    if(res.success){
                        data.data.forEach(item=>item.selected = true);
                        data.selectedNum = data.data.length;
                    }
                    onmessage(res);
                }).catch(res=>{
                    onmessage(res);
                }))
            },
            onDeSell:()=>{
                useSocket().then(socket=>socket.rpc('sel.desel',{store_id: storeId}).then(res=>{
                    if(res.success){
                        data.data.forEach(item=>item.selected = !item.selected);
                        data.selectedNum = data.data.length - data.selectedNum;
                    }
                    onmessage(res);
                }).catch(res=>{
                    onmessage(res);
                }))
            },
            onCancelSel:()=>{
                useSocket().then(socket=>socket.rpc('sel.clear',{store_id: storeId}).then(res=>{
                    if(res.success){
                        data.data.forEach(item=>item.selected = false);
                        data.selectedNum = 0;
                    }
                    onmessage(res);
                }).catch(res=>{
                    onmessage(res);
                }))
            },
            ShowInOutDialog:(isIn)=>{
                UiShowDialog(InOutDialog, {storeId, stores:props.stores, mh:props.mh,isIn}).then(res=>{
                    methods.onSearch();
                }).catch(res=>{});
            },
            ShowRackonDialog:(isOn)=>{
                UiShowDialog(RackOnDialog,{isOn, storeId, stores:props.stores,mh:props.mh}).then(res=>{

                }).catch(res=>{

                })
            },
            ShowStockCheckDialog:()=>{
                UiShowDialog(StoreCheckDialog, {stores:props.stores}).then(res=>{
                    methods.onSearch();
                }).catch(res=>{})
            },
            rmbFormatter:(r,c,v)=>{
                return rmbFormat(v, 2);
            }
        };
        if(props.show){
            inited = true;
            init();
        }

        watch(()=>props.show,(v)=>{
            if(v && !inited){
                inited = true;
                init();
            }
        })

        return {
            elToolbar,
            ...toRefs(data),
            ...methods,
            load,
        }
    }
}
</script>
<style lang="scss">
.co-toolbar{
    .co-cat-select{
        max-width: 9rem;
    }
    .co-onsale-select{max-width: 7rem;}
    .el-form-item{ margin-bottom: 0;}
    .co-search-input{width:12rem;}
}

.el-table__header{
    .el-link{font-size: .75rem;font-weight: bold;line-height:1.5rem;}
}

</style>